package com.outsourcing.bottle.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.ref.WeakReference;
import java.util.HashMap;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aviary.android.feather.Constants;
import com.aviary.android.feather.FeatherActivity;
import com.google.gson.Gson;
import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.SplashActivity;
import com.outsourcing.bottle.db.LoginUserInfoTable;
import com.outsourcing.bottle.db.OtherConfigTable;
import com.outsourcing.bottle.domain.LoginUserInfo;
import com.outsourcing.bottle.domain.LoginUserInfoEntry;
import com.outsourcing.bottle.domain.OtherConfigEntry;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.remoteimage.RemoteImageView;
import com.outsourcing.bottle.util.ActivityManager;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BasicUIEvent;
import com.outsourcing.bottle.util.GetFileSize;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.TextUtil;
import com.outsourcing.bottle.util.UICore;
import com.outsourcing.bottle.util.Utility;
/**
 * 
 * @author 06peng
 *
 */
public class SettingActivity extends BasicActivity implements BasicUIEvent, OnClickListener {

	private final int logout = 1;
	private final int logout_success = 2;
	private final int logout_error = 3;
	private final int activity_result_camara_with_data = 1006;
	private final int activity_result_pick_with_data = 5;
	private final int set_avatar = 6;
	private final int set_avatar_success = 7;
	private final int set_avatar_error = 8;
	private final int init_login_userinfo = 9;
	private final int activity_result_aviary = 10;
	
	private ImageView backView;
	private ImageView avatarView;
	private Button logoutView;
	
	private Bitmap bitMap;
	private File picFile;
	public final static int REQUEST_WIDTH = 600;
	
	private RelativeLayout avatarLayout;
	private RelativeLayout doingLayout;
	private RelativeLayout passwordLayout;
	private RelativeLayout basicLayout;
//	private RelativeLayout contactLayout;
	private RelativeLayout educationLayout;
	private RelativeLayout workLayout;
	private RelativeLayout groupLayout;
	private RelativeLayout feedbackLayout;
//	private RelativeLayout noticeLayout;
//	private RelativeLayout notive_voiceLayout;
//	private RelativeLayout vibrationLayout;
//	private ImageView noticeView;
//	private ImageView notive_voiceView;
//	private ImageView vibrationView;
	
	private LoginUserInfoEntry userEntry;
	private OtherConfigEntry ocEntry;
	
	static final int targetBytes = 65000;
	static final int targetShortSide = 400;
	static final int targetLongSide = 480;
	
	private WeakReference<Bitmap> bitmapResult = null;
	
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.setting);
		initWidget();
		
		UICore.eventTask(this, this, init_login_userinfo, "init_login_info", null);
	}
	
	private void initLoginUserInfo() {
		LoginUserInfoTable userTable = new LoginUserInfoTable();
		userEntry = userTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid());
		if (userEntry != null) {
			bitMap = HttpUtils.getBitmapFromUrl(this, userEntry.getAvatar());
		} else {
			getLoginUserInfo();
			if (userEntry != null) {
				bitMap = HttpUtils.getBitmapFromUrl(this, userEntry.getAvatar());
			} 
		}
		OtherConfigTable ot = new OtherConfigTable();
		ocEntry = ot.getBottleOtherConfig();
		handler.sendEmptyMessage(init_login_userinfo);
	}
	
	private void getLoginUserInfo() {
		StringBuffer url = new StringBuffer(UrlConfig.get_loginuser_info);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());

		try {
			String result = HttpUtils.doGet(url.toString());
			if (result == null) {
				return;
			}
			Gson gson = new Gson();
			LoginUserInfo loginUserInfo = gson.fromJson(result, LoginUserInfo.class);
			if (null != loginUserInfo && null != loginUserInfo.getResults() && loginUserInfo.getResults().getAuthok() == 1) {
				LoginUserInfoTable loginUserInfoTable = new LoginUserInfoTable();
				if (null != loginUserInfoTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid())) {
					loginUserInfoTable.deleteLoginUserInfoById(AppContext.getInstance().getLogin_uid());
					loginUserInfoTable.saveLoginUserInfo(loginUserInfo
							.getLoginuser_info(), AppContext.getInstance().getLogin_uid());
				} else {
					loginUserInfoTable.saveLoginUserInfo(loginUserInfo
							.getLoginuser_info(), AppContext.getInstance().getLogin_uid());
				}
				userEntry = loginUserInfoTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void initWidget() {
		LoginUserInfoTable userTable = new LoginUserInfoTable();
		userEntry = userTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid());
		if (userEntry.getBasicinfo_fullfill() == 1) {
			((LinearLayout) findViewById(R.id.setting_basic_tips_layout)).setVisibility(View.GONE);
		} else {
			((LinearLayout) findViewById(R.id.setting_basic_tips_layout)).setVisibility(View.VISIBLE);
			((TextView)findViewById(R.id.tv_profile_tips)).setText(userEntry.getBasicinfo_tip());
		}
		RemoteImageView img_head = (RemoteImageView) findViewById(R.id.iv_author_photo);
		String avatar = userTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid()).getAvatar();
		if (TextUtil.notEmpty(avatar)) {
			img_head.setDefaultImage(R.drawable.avatar_default_small);
			img_head.setImageUrl(avatar);
		}
		
		backView = (ImageView) findViewById(R.id.topbar_back);
		backView.setOnClickListener(this);
		logoutView = (Button) findViewById(R.id.logout);
		logoutView.setOnClickListener(this);
		avatarView = (ImageView) findViewById(R.id.setting_avatar_image);
		
		avatarLayout = (RelativeLayout) findViewById(R.id.setting_avatar_layout);
		avatarLayout.setOnClickListener(this);
		doingLayout = (RelativeLayout) findViewById(R.id.setting_mood_layout);
		doingLayout.setOnClickListener(this);
		passwordLayout = (RelativeLayout) findViewById(R.id.setting_password_layout);
		passwordLayout.setOnClickListener(this);
		basicLayout = (RelativeLayout) findViewById(R.id.setting_basic_profile_layout);
		basicLayout.setOnClickListener(this);
//		contactLayout = (RelativeLayout) findViewById(R.id.setting_contact_layout);
//		contactLayout.setOnClickListener(this);
		educationLayout = (RelativeLayout) findViewById(R.id.setting_education_layout);
		educationLayout.setOnClickListener(this);
		workLayout = (RelativeLayout) findViewById(R.id.setting_work_layout);
		workLayout.setOnClickListener(this);
		groupLayout = (RelativeLayout) findViewById(R.id.setting_friend_group_layout);
		groupLayout.setOnClickListener(this);
		feedbackLayout = (RelativeLayout) findViewById(R.id.setting_feed_layout);
		feedbackLayout.setOnClickListener(this);
//		noticeLayout = (RelativeLayout) findViewById(R.id.setting_notification_layout);
//		noticeLayout.setOnClickListener(this);
//		notive_voiceLayout = (RelativeLayout) findViewById(R.id.setting_sound_layout);
//		notive_voiceLayout.setOnClickListener(this);
//		vibrationLayout = (RelativeLayout) findViewById(R.id.setting_vibration_layout);
//		vibrationLayout.setOnClickListener(this);
//		noticeView = (ImageView) findViewById(R.id.setting_notification_image);
//		notive_voiceView = (ImageView) findViewById(R.id.setting_sound_image);
//		vibrationView = (ImageView) findViewById(R.id.setting_vibration_image);
		
		RelativeLayout about_us = (RelativeLayout)findViewById(R.id.setting_aboutus_layout);
		about_us.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
			    Intent intent= new Intent();        
			    intent.setAction("android.intent.action.VIEW");    
			    Uri content_url = Uri.parse("http://www.mobibottle.com");   
			    intent.setData(content_url);  
			    startActivity(intent);
			}
		});
		
//		SharedPreferences preferences = getSharedPreferences("Preferences_config", Activity.MODE_APPEND);
//    	int notice = preferences.getInt("notice", 1);
//    	int notice_voice = preferences.getInt("notice_voice", 1);
//    	int vibration = preferences.getInt("vibration", 1);
    	
//		if (notice == 1) {
//			noticeView.setBackgroundResource(R.drawable.select_red);
//		} else {
//			noticeView.setBackgroundResource(R.drawable.select_gray);
//		}
//		if (notice_voice == 1) {
//			notive_voiceView.setBackgroundResource(R.drawable.select_red);
//		} else {
//			notive_voiceView.setBackgroundResource(R.drawable.select_gray);
//		}
//		if (vibration == 1) {
//			vibrationView.setBackgroundResource(R.drawable.select_red);
//		} else {
//			vibrationView.setBackgroundResource(R.drawable.select_gray);
//		}
		
	}
	
	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case logout:
			logout();
			break;
		case set_avatar:
			setAvatar();
			break;
		case init_login_userinfo:
			initLoginUserInfo();
			break;
		default:
			break;
		}
	}
	
	@Override
	public void onClick(View v) {
		if (v == backView) {
			finish();
		} else if (v == logoutView) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(getString(R.string.setting_islogout));
			builder.setPositiveButton(getString(R.string.confirm_ok), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					UICore.eventTask(SettingActivity.this, SettingActivity.this, logout, "logout", null);
				}
			});
			builder.setNegativeButton(getString(R.string.confirm_cancel), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			builder.show();
		} else if (v == avatarLayout) {
			doPickPhotoAction();
		} else if (v == groupLayout) {
			Intent intent = new Intent(this, ManagerGroupActivity.class);
			startActivity(intent);
		} else if (v == basicLayout) {
			Intent intent = new Intent(this, SettingBasicActivity.class);
			startActivity(intent);
		} else if (v == passwordLayout) {
			Intent intent = new Intent(this, SettingPasswordActivity.class);
			startActivity(intent);
		} 
//		else if (v == contactLayout) {
//			Intent intent = new Intent(this, SettingContactActivity.class);
//			startActivity(intent);
//		} 
		else if (v == educationLayout) {
			Intent intent = new Intent(this, SettingEducationActivity.class);
			startActivity(intent);
		} else if (v == workLayout) {
			Intent intent = new Intent(this, SettingCompanyActivity.class);
			startActivity(intent);
		} else if (v == doingLayout) {
			Intent intent = new Intent(this, ExpandEditActivity.class);
			Bundle extras = new Bundle();
			extras.putString("from_type", AppContext.SET_DOING);
			intent.putExtras(extras);
			startActivity(intent);
		} else if (v == feedbackLayout) {
			Intent intent = new Intent(this, ExpandEditActivity.class);
			Bundle extras = new Bundle();
			extras.putString("from_type", AppContext.SEND_MESSAGE);
			extras.putInt("ouid", ocEntry.getFeedback_uid());
			intent.putExtras(extras);
			startActivity(intent);
		}
//		else if (v == noticeLayout) {
//			SharedPreferences preferences = getSharedPreferences("Preferences_config", Activity.MODE_APPEND);
//	    	int notice = preferences.getInt("notice", 1);
//			if (notice == 1) {
//				PushService.actionStop(getApplicationContext());
//				saveConfig("notice", 0);
//				noticeView.setBackgroundResource(R.drawable.select_gray);
//			} else {
//				PushService.actionStart(getApplicationContext());
//				saveConfig("notice", 1);
//				noticeView.setBackgroundResource(R.drawable.select_red);
//			}
//		} else if (v == notive_voiceLayout) {
//			SharedPreferences preferences = getSharedPreferences("Preferences_config", Activity.MODE_APPEND);
//	    	int notice_voice = preferences.getInt("notice_voice", 1);
//			if (notice_voice == 1) {
//				saveConfig("notice_voice", 0);
//				notive_voiceView.setBackgroundResource(R.drawable.select_gray);
//			} else {
//				saveConfig("notice_voice", 1);
//				notive_voiceView.setBackgroundResource(R.drawable.select_red);
//			}
//		} else if (v == vibrationLayout) {
//			SharedPreferences preferences = getSharedPreferences("Preferences_config", Activity.MODE_APPEND);
//	    	int vibration = preferences.getInt("vibration", 1);
//			if (vibration == 1) {
//				saveConfig("vibration", 0);
//				vibrationView.setBackgroundResource(R.drawable.select_gray);
//			} else {
//				saveConfig("vibration", 1);
//				vibrationView.setBackgroundResource(R.drawable.select_red);
//			}
//		}
	}
	
//	private void saveConfig(String type, int value) {
//		SharedPreferences preferences = getSharedPreferences("Preferences_config", Activity.MODE_APPEND);
//		Editor editor = preferences.edit();
//		editor.putInt(type, value);
//		editor.commit();
//	}
	
	private void logout() {
		String url = UrlConfig.logout;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			if (result != null) {
				JSONObject obj = new JSONObject(result);
				JSONObject resultObj = obj.getJSONObject("results");
				int success = resultObj.getInt("success");
				if (success == 0) {
					String errmsg = resultObj.getString("errmsg");
					Message msg = Message.obtain(handler, logout_error, errmsg);
					handler.sendMessage(msg);
				} else {
					AppContext.getInstance().setLogin_uid(0);
					AppContext.getInstance().setLogin_token(null);
					SharedPreferences preferences = getSharedPreferences("Preferences_userinfo", Activity.MODE_APPEND);
					Editor editor = preferences.edit();
					editor.putInt("login_uid", 0);
					editor.putString("login_token", null);
					editor.commit();
					String successmsg = resultObj.getString("successmsg");
					Message msg = Message.obtain(handler, logout_success, successmsg);
					handler.sendMessage(msg);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void setAvatar() {
		String url = UrlConfig.set_avatar;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
        try {
            HashMap<String, File> filesMap = new HashMap<String, File>();
            if (picFile != null) {
    			filesMap.put("pic", picFile);
    		}
            GetFileSize g = new GetFileSize();
            System.out.println(">>>>>>>>avatar size:" + g.FormetFileSize(g.getFileSizes(picFile)));
            String result = HttpUtils.post(url, paramsMap, filesMap);
            JSONObject object = new JSONObject(result);
        	JSONObject resultObj = object.getJSONObject("results");
        	int success = resultObj.getInt("success");
        	if (success == 0) {
        		String errmsg = resultObj.getString("errmsg");
        		Message msg = Message.obtain(handler, set_avatar_error, errmsg);
        		handler.sendMessage(msg);
        	} else {
        		getLoginUserInfo();
        		String successmsg = resultObj.getString("successmsg");
				Message msg = Message.obtain(handler, set_avatar_success, successmsg);
				handler.sendMessage(msg);
        	}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void doPickPhotoAction() {
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
		String cancel = getString(R.string.bt_title_back);
		String[] choices;
		choices = new String[2];
		choices[0] = getString(R.string.expand_edit_take_photo); // 拍照
		choices[1] = getString(R.string.expand_edit_choose_photo); // 从相册中选择
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
		builder.setTitle(R.string.expand_edit_photo_title);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						switch (which) {
						case 0:
							String status = Environment.getExternalStorageState();
							if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
								doTakePhoto();// 用户点击了从照相机获取
							}
							break;
						case 1:
							doPickPhotoFromGallery();// 从相册中去获取
							break;
						}
					}
				});
		builder.setNegativeButton(cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}

				});
		builder.create().show();
	}

	/**
	 * 拍照获取图片
	 * 
	 */
	protected void doTakePhoto() {
		try {
		    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		    File pictureFileDir = new File(Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
            if (!pictureFileDir.exists()) {
                pictureFileDir.mkdirs();
            }
            picFile = new File(pictureFileDir, "upload.jpeg");
            Uri pictureUri = Uri.fromFile(picFile);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
            startActivityForResult(cameraIntent, activity_result_camara_with_data);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 从本地手机中选择图片
	 */
//	private void doSelectImageFromLoacal(){
//		Intent localIntent = new Intent();
//		localIntent.setType("image/*");
//		localIntent.setAction("android.intent.action.GET_CONTENT");
//        Intent localIntent2 = Intent.createChooser(localIntent, getString(R.string.expand_edit_choose_photo));
//        startActivityForResult(localIntent2, activity_result_pick_with_data);
//	}
	
	// 封装请求Gallery的intent
	public Intent getPhotoPickIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 320);
		intent.putExtra("outputY", 320);
		intent.putExtra("return-data", true);
		return intent;
	}
	
	// 请求Gallery程序
	protected void doPickPhotoFromGallery() {
		try {
			// Launch picker to choose photo for selected contact
			final Intent intent = getPhotoPickIntent();
			startActivityForResult(intent, activity_result_pick_with_data);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	protected void doCropPhoto(File f) {
		try {
			// 启动gallery去剪辑这个照片
			final Intent intent = getCropImageIntent(Uri.fromFile(f));
			startActivityForResult(intent, activity_result_pick_with_data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	* Constructs an intent for image cropping. 调用图片剪辑程序
	*/
	public Intent getCropImageIntent(Uri photoUri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(photoUri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 320);
		intent.putExtra("outputY", 320);
		intent.putExtra("return-data", true);
		return intent;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case activity_result_pick_with_data: //从本地选择图片
			if (data == null) {
				return;
			}
			bitMap = data.getParcelableExtra("data");
            try {
                File pictureFileDir = new File(Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
                if (!pictureFileDir.exists()) {
                    pictureFileDir.mkdirs();
                }
                picFile = new File(pictureFileDir, "upload.jpeg");
                FileOutputStream ous = new FileOutputStream(picFile);
                bitMap.compress(Bitmap.CompressFormat.JPEG, 100, ous);
            	if ( !Utility.isExternalStorageAvilable() ) {
    				return;
    			}
    			Uri fileUri = Uri.fromFile(picFile);
    			Intent newIntent = new Intent( this, FeatherActivity.class );
    			newIntent.putExtra( "From_Type", Constants.ACTIVITY_AVATAR );
    			newIntent.setData( fileUri );
    			newIntent.putExtra( "API_KEY", Utility.API_KEY );

    			newIntent.putExtra( "output", Uri.parse( "file://" + picFile.getAbsolutePath() ) );
    			newIntent.putExtra( Constants.EXTRA_OUTPUT_FORMAT, Bitmap.CompressFormat.JPEG.name() );
    			newIntent.putExtra( Constants.EXTRA_OUTPUT_QUALITY, 100 );
    			newIntent.putExtra( Constants.EXTRA_TOOLS_DISABLE_VIBRATION, true );

    			final DisplayMetrics metrics = new DisplayMetrics();
    			getWindowManager().getDefaultDisplay().getMetrics( metrics );
    			int max_size = Math.min( metrics.widthPixels, metrics.heightPixels );
    			max_size = (int) ( (double) max_size / 0.8 );
    			newIntent.putExtra( "max-image-size", max_size );
    			newIntent.putExtra( "effect-enable-borders", true );
    			startActivityForResult(newIntent, activity_result_aviary );
                
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
            	if (null != bitMap && !bitMap.isRecycled()) {
					bitMap.recycle();
					bitMap = null;
				}
            }
			break;
		case activity_result_aviary:
			if (resultCode == RESULT_OK) {
				try {
					File pictureFileDir = new File(Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
		            if (!pictureFileDir.exists()) {
		                pictureFileDir.mkdirs();
		            }
		            picFile = new File(pictureFileDir, "upload.jpeg");

		            FileInputStream in = new FileInputStream(picFile);
					BitmapFactory.Options options1 = new BitmapFactory.Options();
					options1.inPurgeable = true;
					options1.inInputShareable = true;
					options1.inSampleSize = 2;
					try {
						BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean(options1, true);
					} catch (Exception ex) {
						ex.printStackTrace();
					}
					bitmapResult = new WeakReference<Bitmap>(BitmapFactory
							.decodeStream(in, null, options1));
					Bitmap bt = bitmapResult.get();
		            avatarView.setImageBitmap(bt);
		            UICore.eventTask(SettingActivity.this, SettingActivity.this, set_avatar, "set_avatar", null);
						
				} catch (Exception e) {
					e.printStackTrace();
				} finally{
//					if (null!= bitmapResult && null != bitmapResult.get() && !bitmapResult.get().isRecycled()) {
//						bitmapResult.get().recycle();
//						bitmapResult = null;
//					}
				}
	            
			}
			break;
		case activity_result_camara_with_data:  //拍照
			if (picFile == null) {
				File pictureFile = new File(
						Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
				picFile = new File(pictureFile, "upload.jpeg");
			}
			doCropPhoto(picFile);
			break;
		}
	}
	
	protected void onDestroy() {
		super.onDestroy();
		try {
			File uploadFileDir = new File(
					Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
			File file = new File(uploadFileDir, "upload.jpeg");
			if (file.exists()) {
				file.delete();
			}
			if (bitmapResult.get() != null && !bitmapResult.get().isRecycled()) {
				bitmapResult.get().recycle();
				bitmapResult = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	};
	
	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case logout_error:
				onToast((String) msg.obj);
				break;
			case logout_success:
				onToast((String) msg.obj);
				ActivityManager.finishAll();
				AppContext.getInstance().setCurrentItem(1); //
				Intent intent = new Intent(SettingActivity.this, SplashActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				intent.putExtra("init", true);
				startActivity(intent);
				break;
			case set_avatar_error:
				onToast((String) msg.obj);
				break;
			case set_avatar_success:
				onToast((String) msg.obj);
				break;
			case init_login_userinfo:
				avatarView.setImageBitmap(bitMap);
				if (userEntry != null) {
					((TextView) findViewById(R.id.setting_doing_value)).setText(userEntry.getDoing());
				}
				break;
			default:
				break;
			}
		}
		
	};

}
